package com.ld.security.demo.base;

import com.ld.security.common.mybatis.base.vo.DataVo;
import com.ld.security.common.mybatis.base.vo.ExceptionVo;
import com.ld.security.common.tomcat.handler.BaseExceptionHandler;
import com.ld.security.server.admin.modules.gl.entity.GlLogEntity;
import com.ld.security.server.admin.modules.gl.service.IGlLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class AuthServerHandle extends BaseExceptionHandler {


    @Autowired
    private IGlLogService iGlLogService;



    @Override
    public void sendMail(ExceptionVo vo) {
        GlLogEntity e = new GlLogEntity();
        e.setContent(vo.getContent());
        e.setLabel(vo.getLabel());
        e.setLogType(vo.getExType());
        iGlLogService.save(e);

    }

    @ExceptionHandler(value = {IncorrectCredentialsException.class})
    @ResponseBody
    public DataVo IncorrectCredentialsException (IncorrectCredentialsException  ex){

        DataVo dataVo = DataVo.of();
        dataVo.setMessage("密码错误");
        dataVo.setCode(400);
        return dataVo;
    }


    @ExceptionHandler(value = {LockedAccountException .class})
    @ResponseBody
    public DataVo LockedAccountException (LockedAccountException  ex){

        DataVo dataVo = DataVo.of();
        dataVo.setMessage("账号被锁定");
        dataVo.setCode(400);
        return dataVo;
    }




    @ExceptionHandler(value = {UnknownAccountException.class})
    @ResponseBody
    public DataVo UnknownAccountException(UnknownAccountException ex){

        DataVo dataVo = DataVo.of();
        dataVo.setMessage("未知账号");
        dataVo.setCode(400);
        return dataVo;
    }



    @ExceptionHandler(value = {AuthenticationException.class})
    @ResponseBody
    public DataVo AuthenticationException(AuthenticationException ex){
        ex.printStackTrace();


        ExceptionVo vo = new ExceptionVo();

        vo.setLabel("授权异常");
        vo.setExType("授权异常");
        DataVo dataVo = DataVo.of(vo);
        dataVo.setMessage("授权失败,清检查账号或密码");
        dataVo.setCode(400);
        return dataVo;
    }
}
